import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from "path"
import os from 'os'; //提供本地的相关信息
import VueSetupExtend from 'vite-plugin-vue-setup-extend'


// 获取本地ip
function getNetWorkIp() {
  // 打开host
  let needHost = '';
  try {
    let network = os.networkInterfaces();
    for (const dev in network) {
      let iface = network[dev];
      for (let i = 0; i < iface.length; i++) {
        const alias = iface[i];
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          needHost = alias.address;
        }
      }
    }
  } catch (error) {
    needHost = 'localhost';
  }
  return needHost
}
const IP = getNetWorkIp();
console.log('Ip', IP)

// https://vitejs.dev/config/
export default ({ mode }) => {
  const config = loadEnv(mode, process.cwd())
  const isProduction = config.VITE_ENV === "production"
  return defineConfig({
    base: config.VITE_ENV === 'development' ? './' : '/',
    productionSourceMap: !isProduction,
    plugins: [vue(), VueSetupExtend()],
    server: {
      https: false,
      open: false,
      cors: true,
      port: 3003,
      host: "0.0.0.0",
      proxy: {
        '/api': { // 匹配请求路径，
          target: `http://${IP}:3003`, // 代理的目标地址
          // 开发模式，默认的127.0.0.1,开启后代理服务会把origin修改为目标地址
          changeOrigin: true,
          secure: false, // 是否https接口
          ws: false, // 是否代理websockets
          // 路径重写，**** 如果你的后端有统一前缀(如:/api)，就不开启；没有就开启
          // 简单来说，就是是否改路径 加某些东西
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    resolve: {
      alias: {
        '~/': `${resolve(__dirname, 'src')}/`,
        '@': resolve(__dirname, "src"),
        "@assets": resolve(__dirname, "src/assets"),
        "@components": resolve(__dirname, "src/components"),
        "@images": resolve(__dirname, "src/assets/images"),
        "@views": resolve(__dirname, "src/views"),
        "@store": resolve(__dirname, "src/store"),
      }
    }
  })

} 